package br.com.ufpr.util.base;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;

public abstract class SortableListDataProvider<T extends Serializable> extends SortableDataProvider<T, String> {
    private static final long serialVersionUID = 7848125658251363170L;

    private final IModel<ArrayList<T>> listModel;

    public SortableListDataProvider(final IModel<ArrayList<T>> listModel, final SortParam<String> defaultSort) {
        super();
        this.listModel = listModel;
        setSort(defaultSort);
    }

    @Override
    public Iterator<? extends T> iterator(final long first, final long count) {
        sortList(listModel.getObject(), getSort());
        long toIndex = first + count;
        if (toIndex > listModel.getObject().size()) {
            toIndex = listModel.getObject().size();
        }
        return listModel.getObject().subList((int) first, (int) toIndex).listIterator();
    }

    @Override
    public long size() {
        return listModel != null && listModel.getObject() != null ? listModel.getObject().size() : 0;
    }

    @Override
    public IModel<T> model(final T object) {
        return new AbstractReadOnlyModel<T>() {
            private static final long serialVersionUID = -6089443555682344274L;

            @Override
            public T getObject() {
                return object;
            }
        };
    }

    protected abstract void sortList(final ArrayList<T> list, final SortParam<String> sort);

}
